using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Acme.BookStore.Redis;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp;
using Volo.Abp.AspNetCore.Mvc;

namespace Acme.BookStore.Controllers
{
    [RemoteService]
    [Route("api/redis")]
    public class RedisCacheController : AbpControllerBase
    {
        private readonly RedisCacheMonitorService _redisCacheMonitorService;

        public RedisCacheController(RedisCacheMonitorService redisCacheMonitorService)
        {
            _redisCacheMonitorService = redisCacheMonitorService;
        }

        /// <summary>
        /// 获取Redis状态信息
        /// </summary>
        [HttpGet("status")]
        public async Task<RedisStatusDto> GetStatusAsync()
        {
            return await _redisCacheMonitorService.GetStatusAsync();
        }

        /// <summary>
        /// 清除指定模式的缓存
        /// </summary>
        /// <param name="pattern">缓存键模式</param>
        [HttpDelete("clear")]
        [Authorize("admin")]
        public async Task<object> ClearCacheAsync(string pattern)
        {
            var (count, message) = await _redisCacheMonitorService.ClearCacheAsync(pattern);
            return new { count, message };
        }
        
        /// <summary>
        /// 清除所有客户相关缓存
        /// </summary>
        [HttpDelete("clear-kehu-cache")]
        [Authorize("admin")]
        public async Task<object> ClearKehuCacheAsync()
        {
            var (count, message) = await _redisCacheMonitorService.ClearCacheAsync("BookStore:Kehu:*");
            return new { count, message };
        }

        /// <summary>
        /// 获取Redis性能指标
        /// </summary>
        [HttpGet("performance")]
        public async Task<object> GetPerformanceMetricsAsync()
        {
            return await _redisCacheMonitorService.GetPerformanceMetricsAsync();
        }
        
        /// <summary>
        /// 生成测试数据（仅开发环境使用）
        /// </summary>
        [HttpPost("generate-test-data")]
        [Authorize("admin")]
        public async Task<string> GenerateTestDataAsync(int count = 1000)
        {
            if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") != "Development")
            {
                return "此操作仅在开发环境可用";
            }
            
            return await _redisCacheMonitorService.GenerateTestDataAsync(count);
        }
    }
} 